package com.yaorange.jk.web.shiro;

import com.yaorange.jk.entity.Module;
import com.yaorange.jk.entity.Role;
import com.yaorange.jk.entity.User;
import com.yaorange.jk.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class AuthRealm extends AuthorizingRealm {

    private UserService userService;
    //密码匹配器
    private CustomCredentialsMatcher credentialsMatcher;

    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("登录认证中.......");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //从数据库中查询登录的用户信息；
        User user = userService.finfindByUsername(token.getUsername());
        user.getDept().getDeptName();
        //将user里的各个数据获取一下，使 Hibernate lazy 无效，便于view获取数据；
        Set<Role> roleSet = user.getRoleSet();
        for (Role role: roleSet) {
            Set<Module> moduleSet = role.getModuleSet();
            for(Module m:moduleSet){
                m.getCpermission();
            }
        }
        SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());

        return sai;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.fromRealm(this.getName()).iterator().next();
        //用来封装该用户所有的权限
        List<String> permissionList = new ArrayList<>();
        //获取当前用户
        //填充permissionList
        Set<Role> roleSet = user.getRoleSet();
        for (Role role:roleSet) {
            Set<Module> moduleSet = role.getModuleSet();
            for (Module module: moduleSet) {
                permissionList.add(module.getCpermission());
            }
        }
        //将permissionList加入shiro
        result.addStringPermissions(permissionList);
        return result;
    }


    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setCredentialsMatcher(CustomCredentialsMatcher credentialsMatcher) {
        this.credentialsMatcher = credentialsMatcher;
    }

    public CustomCredentialsMatcher getCredentialsMatcher() {
        return credentialsMatcher;
    }


}
